/**
 * AccessLimitFilter.java
 * com.sftz.framework.actionfilter
 * Copyright (c) 2019, 北京科技有限公司版权所有.
*/

package com.sftz.framework.mvc.actionfilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.json.JsonFormat;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionFilter;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.view.ViewWrapper;

import com.sftz.framework.util.SessionReqLimitUtils;
import com.uxuexi.core.web.chain.support.JsonResult;
import com.uxuexi.core.web.view.Utf8JsonTransferView;

/**
 * 接口请求频率过滤器.
 * <p>
 * 用于防止用户频繁请求接口
 * @author 朱晓川
 *
 */
public class AccessLimitFilter implements ActionFilter {

	/*
	 * 1秒5次
	 */

	/**接口请求频率限制时间*/
	private static final long limitSplitTime = 1000;

	/**接口请求频率限制次数*/
	private static final int limitCount = 5;

	@Override
	public View match(ActionContext ac) {
		HttpServletRequest request = Mvcs.getReq();
		HttpSession session = request.getSession();
		boolean limit = SessionReqLimitUtils.limit(limitSplitTime, limitCount, session.getId());
		if (limit) {
			return new ViewWrapper(new Utf8JsonTransferView(new JsonFormat()), JsonResult.error("请勿频繁请求"));
		}

		return null;
	}
}
